using Infratructure;
using Infratructure.Implement;
using Infratructure.Interface;
using MES.Server.API;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using NLog.Web;
using SignalRBackend;
using System.Reflection;
using System.Text;
using Yitter.IdGenerator;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// 注入 HTTP 上下文 HttpContext
builder.Services.AddHttpContextAccessor();

// 添加CORS服务
builder.Services.AddCors(options =>
{
    // 统一的CORS策略
    options.AddPolicy("AllowAll", builder =>
    {
        builder
            .SetIsOriginAllowed(_ => true) // 允许任何源
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials(); // 允许凭证
    });
});

//授权认证（使用JWT）
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
    // 私钥
    var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
    o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        // 验证发布者
        ValidateIssuer = true,
        // 发布者信息
        ValidIssuer = "BeiJingBW",

        // 验证订阅者
        ValidateAudience = true,
        // 订阅者
        ValidAudience = "BeiJingBW",

        // 验证是否过期
        ValidateLifetime = true,

        // 验证私钥
        IssuerSigningKey = new SymmetricSecurityKey(secretByte)
    };
    
    // 处理JWT认证中的事件
    o.Events = new JwtBearerEvents
    {
        OnChallenge = context =>
        {
            // 跳过默认的处理逻辑，防止返回401状态码
            context.HandleResponse();
            
            // 返回自定义的错误信息
            context.Response.StatusCode = 200;
            context.Response.ContentType = "application/json";
            
            // 这里可以返回自定义的错误信息
            var result = System.Text.Json.JsonSerializer.Serialize(new { code = 401, message = "未授权" });
            return context.Response.WriteAsync(result); 
        }
    };
});

//注册全局异常过滤器
builder.Services.AddControllers(x=>x.Filters.Add<ExceptionFilters>());
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(o =>
{
    o.IncludeXmlComments(AppContext.BaseDirectory + "MES.Server.API.xml", true);
    // 显示 授权信息
    o.AddSecurityDefinition("Bearer", new Microsoft.OpenApi.Models.OpenApiSecurityScheme() 
    {
        Description = "输入JWT授权Token：Bearer Token值",
        Name = "Authorization",
        In = Microsoft.OpenApi.Models.ParameterLocation.Header,
        Type = Microsoft.OpenApi.Models.SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    o.AddSecurityRequirement(new Microsoft.OpenApi.Models.OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[]
            {

            }
        }
    });
}
);

// 注册数据库上下文
var mysql = builder.Configuration["MysqlConnectionStrings:mysqlstr"];  //mysql连接字符串
builder.Services.AddDbContext<DateContext>(x => x.UseMySql(mysql, ServerVersion.AutoDetect(mysql)));
//注册仓储
builder.Services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
//注册中介者
builder.Services.AddMediatR(x => x.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
//注册日志
builder.Host.UseNLog();
//注册雪花ID
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());
builder.Services.AddHttpClient();

// 注册和风天气API的HttpClient
builder.Services.AddHttpClient("WeatherApi", client =>
{
    // 不设置BaseAddress，因为我们会使用完整的URL
    // 添加默认的User-Agent头，有些API需要这个
    client.DefaultRequestHeaders.Add("User-Agent", "MES-Weather-Client/1.0");
    // 设置超时时间
    client.Timeout = TimeSpan.FromSeconds(30);
});
//注册Automapper
builder.Services.AddAutoMapper(typeof(AutomapperFiles));

// 将 SignalR 服务添加到依赖注入容器
builder.Services.AddSignalR();
builder.Services.AddControllers();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
 }

    // 在所有中间件之前使用CORS
    app.UseCors("AllowAll");

    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    // 映射 SignalR Hub 终结点
    app.MapHub<MessageHub>("/messageHub");
    app.MapControllers();

    app.Run();






